import 'package:fluro/fluro.dart';
import 'package:flutter/widgets.dart';
import 'package:imperius_insights/entity/department.dart';
import 'package:imperius_insights/events/event-bus.dart';
import 'package:imperius_insights/events/scope-changed-event.dart';
import 'package:imperius_insights/portal/state/indicator/indicator.dart';
import 'package:imperius_insights/portal/state/mobx/store.dart';
import 'package:mobx/mobx.dart';
import 'package:provider/provider.dart';

import 'domain.dart';

part 'view_model_department.g.dart';

class ViewModel = _ViewModelInternal with _$ViewModel;

abstract class _ViewModelInternal with Store, StoreWithLifecycle {
  @observable
  IndicatorState<List<Department>> departments;

  @observable
  String current;

  @override
  onContextAttached(BuildContext context) {
    super.onContextAttached(context);
    final domain = Provider.of<Domain>(context, listen: false);
    departments = IndicatorState<List<Department>>();
    departments.setStatus(status: Status.completed, data: domain.departments);
    restoreCurrentSelect();
  }

  onSelect(Department department) async {
    final domain = Provider.of<Domain>(context, listen: false);
    await domain.deleteCurrentHuman();
    await domain.saveDepartmentId(department.id);
    runInAction(() => current = department.id);
    defaultEventBus.fire(ScopeChangedEvent());
    final router = Provider.of<Router>(context, listen: false);
    router.pop(context);
//    router.navigateTo(context, Paths.scopeHumans,
//        transition: TransitionType.fadeIn);
  }

  restoreCurrentSelect() async {
    final domain = Provider.of<Domain>(context, listen: false);
    final departmentId = await domain.getDepartmentId();
    runInAction(() {
      current = departmentId;
    });
  }

  @override
  onContextDetached(BuildContext context) {
    super.onContextDetached(context);
  }
}
